package com.zz.controller;

import com.zz.domain.StudentMachine;
import com.zz.service.HeartbeatService;
import com.zz.service.StudentMachineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.List;

@Controller
public class TeacherController {
    // 处理来自学生机的ping消息

    @Autowired
    HeartbeatService heartbeatService;
    @Autowired
    StudentMachineService studentMachineService;
    @MessageMapping("/ping")
    @SendTo("/topic/pong")
    public String handlePing(String pingMessage) {
        // 当收到ping消息时，返回pong响应
        System.out.println("收到学生机: " + pingMessage+"：向学生机回复pong完成");
        Date da = new Date();
        //查询数据表id，时间，更改最后心跳
        List<StudentMachine> student =  studentMachineService.ge();
        // 遍历并更新每个学生机的心跳时间
        for (StudentMachine studen : student) {
            System.out.println("准备更新时间，id=" + studen.getMachineId() +
                    ", machineId=" + studen.getMachineId() +
                    ", 时间=" + da);
            studentMachineService.in(da, studen.getMachineId());
            studentMachineService.getConnectedStudentCount();
        }
        return "pong";
    }
}
